package com.mohe.zhihui.action;

import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mohe.zhihui.model.Admin;
import com.mohe.zhihui.service.interfaces.IAdmin;
import com.mohe.zhihui.utils.MD5Util;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 管理员Action
 * 
 * @author wcx
 * 
 */
public class UserAction extends ActionSupport {

	private static final long serialVersionUID = 5189781421792532180L;

	private IAdmin adminServ;

	private String flag;

	public IAdmin getAdminServ() {
		return adminServ;
	}

	public void setAdminServ(IAdmin adminServ) {
		this.adminServ = adminServ;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

//	public UserAction() {
//		super();
//		// 这种方式可以暂时解决spring无法自动注入造成的空指针问题
//		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//		adminServ = (IAdmin) ac.getBean("IAdmin");
//	}

	/**
	 * 登录
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public String login() throws NoSuchAlgorithmException {

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();

		// 登录参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return "login.jsp";
		}
		if (null != password) {
			password = MD5Util.encrypt(password);
		}

		Admin admin = adminServ.getAdminByPwd(username, password);

		if (null != admin) {
			session.setAttribute("adminKey", admin.getTimeKey());
			session.setAttribute("admin", admin);
			// Role role =roleServ.getRoleById(admin.getRole().getTimeKey());
			// session.setAttribute("role", role);
			return "index.jsp";
		} else {
			flag = "loginNO";
		}

		return "login.jsp";

	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	public String loginOut() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute("adminKey");
		session.removeAttribute("admin");
		// session.removeAttribute("role");
		return "login.jsp";
	}

}
